#!/bin/sh

# This file checks for clam av to see if it is running.  It will restart it if it is not.
checkproc()
{
	# checkproc <process name> <restart command>

	BASEN=`/bin/basename $1`
	
	if [ $# -lt 2 ]
	then
		echo "Not enough parmeters passed to $0"
	else

		PK=`ps -ax | grep -v grep | grep -c "$1"`
		if [ "$PK" == "0" ]
		then 

			if [ -f /var/run/checkprocess/$BASEN ]
			then
				CNT=`cat /var/run/checkprocess/$BASEN`
				if [ "$CNT" == "" ]
				then 
					CNT=0
				fi
			else
				CNT=0
			fi
			if [ $CNT -gt $RESTARTLIMIT ]
			then
				echo "We have attempted to restart the process $1 on `/bin/hostname` at least $CNT times but it does not appear to be running still.  Please check into this on `/bin/hostname`" | /bin/mail -s "Error restarting process: $1 at `/bin/date` on `/bin/hostname`" 	$ALERTEMAIL,$OPSEMAIL
				/usr/bin/logger -t "$0" "Process not running: $1 - Restart limit reached - $CNT"
			else
		
				$2 | mail -s "$1 was not running at `/bin/date` on `/bin/hostname`. Process restarted" $ALERTEMAIL
				/usr/bin/logger -t "$0" "Process not running: $1 - Attempted automatic restart"
				CNT=`/usr/bin/expr $CNT + 1`
			fi
		else 
			CNT=0
		fi
		echo $CNT > /var/run/checkprocess/$BASEN
	fi
}

# start of main - #
#export ALERTEMAIL=yourname@domain.net
#export OPSEMAIL=yourname@domain.net
export RESTARTLIMIT=10

if [ ! -f /var/run/checkprocess ]
then
	mkdir -p /var/run/checkprocess
fi


checkproc clamd "/etc/rc.d/init.d/clamav restart"
checkproc freshclam "/etc/rc.d/init.d/clamav restart"
checkproc assp.pl "/etc/init.d/assp start"

